package Multithread;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownloadSpeed {
	static long length = 0;
	static boolean isStop = true;

	class GetFile extends Thread {
		String file = "";

		public GetFile(String file) {
			this.file = file;
		}

		public void run() {
			try {
				downloadNet(file);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}
	}

	class GetLength extends Thread {
		public void run() {
			try {
				while (isStop) {
					long size1 = length;
					Thread.sleep(1000);
					long size2 = length;
					double speeds = (size2 - size1) / 1024.0;
					BigDecimal b = new BigDecimal(speeds);
					double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP)
							.doubleValue(); // 保留两位小数
					System.out.println(f1 + "KB/S");
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

	public void StartDownload() {
		GetFile f = new GetFile(
				"http://dlsw.baidu.com/sw-search-sp/soft/2e/10849/wrar501sc.1392692257.exe");
		GetLength L = new GetLength();
		f.start();
		L.start();
	}

	public static void main(String[] args) {
		DownloadSpeed d = new DownloadSpeed();
		d.StartDownload();
	}

	public static void downloadNet(String urlpath) throws MalformedURLException {
		// 下载网络文件
		int bytesum = 0;
		int byteread = 0;
		URL url = new URL(urlpath);
		try {
			URLConnection conn = url.openConnection();
			InputStream inStream = conn.getInputStream();
			FileOutputStream fs = new FileOutputStream("c:\\a.exe");
			byte[] buffer = new byte[1024];
			while ((byteread = inStream.read(buffer)) != -1) {
				length += (long) byteread;
				fs.write(buffer, 0, byteread);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			isStop = false;
		}
	}
}
